package com.smartparking.controller;

import com.smartparking.model.AppUser;
import com.smartparking.model.enums.Role;
import com.smartparking.repository.UserRepository;
import com.smartparking.security.JwtUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public AuthController(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        String role = body.get("role");

        if (username == null || password == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "username and password required"));
        }
        if (userRepository.findByUsername(username).isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("error", "username exists"));
        }
        AppUser u = new AppUser();
        u.setUsername(username);
        u.setPasswordHash(passwordEncoder.encode(password));
        u.setRole(role != null ? Role.ADMIN : Role.USER);

        userRepository.save(u);
        return ResponseEntity.ok(Map.of("msg", "registered"));
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        AppUser u = userRepository.findByUsername(username).orElse(null);
        if (u == null) return ResponseEntity.status(401).body(Map.of("error", "invalid"));
        if (!passwordEncoder.matches(password, u.getPasswordHash())) {
            return ResponseEntity.status(401).body(Map.of("error", "invalid"));
        }
        String token = jwtUtil.generateToken(username);
        Map<String, String> res = new HashMap<>();
        res.put("token", token);
        return ResponseEntity.ok(res);
    }
}
